///*
// * To change this template, choose Tools | Templates
// * and open the template in the editor.
// */
//package action.paypal;
//
//import cart.ShoppingCart;
//import cart.ShoppingCartItem;
//import static com.opensymphony.xwork2.Action.ERROR;
//import static com.opensymphony.xwork2.Action.SUCCESS;
//import com.opensymphony.xwork2.ActionContext;
//import com.opensymphony.xwork2.ActionSupport;
//import database.TransactionDAO;
//import java.io.IOException;
//import java.util.ArrayList;
//import java.util.Date;
//import java.util.HashMap;
//import java.util.Iterator;
//import java.util.List;
//import java.util.Map;
//import java.util.logging.Level;
//import java.util.logging.Logger;
//import model.Customer;
//import model.Order;
//import org.apache.struts2.convention.annotation.Action;
//import org.apache.struts2.convention.annotation.Namespace;
//import org.apache.struts2.convention.annotation.Result;
//import urn.ebay.api.PayPalAPI.DoExpressCheckoutPaymentReq;
//import urn.ebay.api.PayPalAPI.DoExpressCheckoutPaymentRequestType;
//import urn.ebay.api.PayPalAPI.DoExpressCheckoutPaymentResponseType;
//import urn.ebay.api.PayPalAPI.GetExpressCheckoutDetailsReq;
//import urn.ebay.api.PayPalAPI.GetExpressCheckoutDetailsRequestType;
//import urn.ebay.api.PayPalAPI.GetExpressCheckoutDetailsResponseType;
//import urn.ebay.api.PayPalAPI.PayPalAPIInterfaceServiceService;
//import urn.ebay.api.PayPalAPI.SetExpressCheckoutReq;
//import urn.ebay.api.PayPalAPI.SetExpressCheckoutRequestType;
//import urn.ebay.api.PayPalAPI.SetExpressCheckoutResponseType;
//import urn.ebay.apis.CoreComponentTypes.BasicAmountType;
//import urn.ebay.apis.eBLBaseComponents.AddressType;
//import urn.ebay.apis.eBLBaseComponents.CurrencyCodeType;
//import urn.ebay.apis.eBLBaseComponents.DoExpressCheckoutPaymentRequestDetailsType;
//import urn.ebay.apis.eBLBaseComponents.ErrorType;
//import urn.ebay.apis.eBLBaseComponents.GetExpressCheckoutDetailsResponseDetailsType;
//import urn.ebay.apis.eBLBaseComponents.PayerInfoType;
//import urn.ebay.apis.eBLBaseComponents.PaymentActionCodeType;
//import urn.ebay.apis.eBLBaseComponents.PaymentDetailsItemType;
//import urn.ebay.apis.eBLBaseComponents.PaymentDetailsType;
//import urn.ebay.apis.eBLBaseComponents.PaymentInfoType;
//import urn.ebay.apis.eBLBaseComponents.PersonNameType;
//import urn.ebay.apis.eBLBaseComponents.SellerDetailsType;
//import urn.ebay.apis.eBLBaseComponents.SetExpressCheckoutRequestDetailsType;
//
///**
// *
// * @author Thai Ha Cong
// */
//@Namespace("/")
//public class PaypalAction extends ActionSupport {
//
//    private String token;
//    private Map<String, String> map;
//
//    public PaypalAction() {
//        //
//        map = new HashMap<String, String>();
//        map.put("mode", "sandbox");
//        map.put("acct1.UserName", "escape2008v8-facilitator_api1.gmail.com");
//        map.put("acct1.Password", "1379621728");
//        map.put("acct1.Signature", "AFcWxV21C7fd0v3bYYYRCpSSRl31AR2KCX-3OhGFx0W4.bDJ6vPwhh0J");
////        map.put("acct1.AppId", "");
//        map.put("http.ConnectionTimeOut", "5000");
//        map.put("http.Retry", "2");
//        map.put("http.ReadTimeOut", "30000");
//        map.put("http.MaxConnection", "1000");
//        map.put("http.IPAddress", "127.0.0.1");
//        map.put("http.UseProxy", "false");
//        map.put("http.GoogleAppEngine", "false");
//    }
//
//    public String getToken() {
//        return token;
//    }
//
//    public void setToken(String token) {
//        this.token = token;
//    }
//
//    @Override
//    public String execute() throws Exception {
//        return SUCCESS;
//    }
//
//    @Action(value = "setExpressCheckout", results = {
//        @Result(name = "success", location = "/redirect/rdrPaypalLogin.jsp"),
//        @Result(name = "error", location = "/shoppingCart.jsp")
//    })
//    public String setExpressCheckout() {
//        Map session = ActionContext.getContext().getSession();
//        ShoppingCart sc = (ShoppingCart) session.get("shoppingCart");
//        List<ShoppingCartItem> scis = sc.getShoppingCartItemList();
//
//        SetExpressCheckoutReq secr = new SetExpressCheckoutReq();
//        SetExpressCheckoutRequestType secrt = new SetExpressCheckoutRequestType();
//
//        //
//        SetExpressCheckoutRequestDetailsType secrdt = new SetExpressCheckoutRequestDetailsType();
//        secrdt.setReturnURL("http://localhost:8084/OnlineShopping/getExpressCheckout");
//        secrdt.setCancelURL("http://localhost:8084/OnlineShopping/viewShoppingCart");
//
//        List<PaymentDetailsType> pdts = new ArrayList<PaymentDetailsType>();
//        //
//        PaymentDetailsType pdt = new PaymentDetailsType();
//
//        pdt.setPaymentAction(PaymentActionCodeType.SALE);
//
//        BasicAmountType bat = new BasicAmountType(CurrencyCodeType.USD, "" + String.format("%1$,.2f", sc.getTotalAmount()));
//        pdt.setOrderTotal(bat);
//        pdt.setItemTotal(bat);
////        pdt.setHandlingTotal(new BasicAmountType(CurrencyCodeType.USD, "0"));
////        pdt.setInsuranceTotal(new BasicAmountType(CurrencyCodeType.USD, "0"));
////        pdt.setShippingTotal(new BasicAmountType(CurrencyCodeType.USD, "0"));
//
//        SellerDetailsType sdt = new SellerDetailsType();
//        sdt.setPayPalAccountID("escape2008v8-facilitator@gmail.com");
//        pdt.setSellerDetails(sdt);
//
//        //
//        List<PaymentDetailsItemType> pdits = new ArrayList<PaymentDetailsItemType>();
//
//        for (ShoppingCartItem sci : scis) {
//            PaymentDetailsItemType pdit = new PaymentDetailsItemType();
//
//            pdit.setAmount(new BasicAmountType(CurrencyCodeType.USD, "" + sci.getPrice()));
//            pdit.setQuantity(sci.getQuantity());
//            pdit.setName(sci.getProduct().getName());
//            pdit.setNumber(sci.getProduct().getCode());
//            pdit.setDescription(sci.getProduct().getSummary());
//
//            pdits.add(pdit);
//        }
//
//        //
//        pdt.setPaymentDetailsItem(pdits);
//
//        pdts.add(pdt);
//
//        //
//        secrdt.setPaymentDetails(pdts);
//        secrt.setSetExpressCheckoutRequestDetails(secrdt);
//        secr.setSetExpressCheckoutRequest(secrt);
//
//
//        try {
//            PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(map);
//
//            SetExpressCheckoutResponseType response = service.setExpressCheckout(secr);
//
//            if (response.getAck().getValue().equalsIgnoreCase("success")) {
//                token = response.getToken();
//
//                System.out.println("EC Token:" + token);
//
//                return SUCCESS;
//            } else {
//                List<ErrorType> errorTypes = response.getErrors();
//                System.out.println("API Error Message : " + errorTypes.get(0).getLongMessage());
//
//                addActionError("Cannot Checkout with Paypal at the moment. (Set)");
//            }
//        } catch (Exception ex) {
//            Logger.getLogger(PaypalAction.class.getName()).log(Level.SEVERE, null, ex);
//        }
//
//        return ERROR;
//    }
//
//    @Action(value = "getExpressCheckout", results = {
//        @Result(name = "success", location = "/redirect/rdrConfirmEC.jsp"),
//        @Result(name = "error", location = "/shoppingCart.jsp")
//    })
//    public String getExpressCheckout() {
//        Map session = ActionContext.getContext().getSession();
//
//        Map parametersMap = ActionContext.getContext().getParameters();
//        //
//        if (parametersMap.containsKey("token")) {
//            String[] tokenArray = (String[]) parametersMap.get("token");
//            token = tokenArray[0];
//        }
//
//        String payerID = "";
//        if (parametersMap.containsKey("PayerID")) {
//            String[] payerIDArray = (String[]) parametersMap.get("PayerID");
//            payerID = payerIDArray[0];
//        }
//
//        //
//        GetExpressCheckoutDetailsReq gecdr = new GetExpressCheckoutDetailsReq();
//        GetExpressCheckoutDetailsRequestType gecdrt = new GetExpressCheckoutDetailsRequestType(token);
//        gecdr.setGetExpressCheckoutDetailsRequest(gecdrt);
//
//        try {
//            PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(map);
//
//            GetExpressCheckoutDetailsResponseType response = service.getExpressCheckoutDetails(gecdr);
//
//            if (response.getAck().getValue().equalsIgnoreCase("success")) {
//                GetExpressCheckoutDetailsResponseDetailsType responseDetailsType = response.getGetExpressCheckoutDetailsResponseDetails();
////                responseDetailsType.getPayerInfo().getPayerName();
////                responseDetailsType.getBuyerMarketingEmail();
//
//                Customer customer = new Customer();
//
//                PayerInfoType payerInfoType = responseDetailsType.getPayerInfo();
//                //
//                PersonNameType personNameType = payerInfoType.getPayerName();
//                customer.setFirstName(personNameType.getFirstName() + " " + personNameType.getLastName());
//                customer.setLastName("Paypal ID: " + payerInfoType.getPayerID());
//                //
//                AddressType addressType = payerInfoType.getAddress();
//                customer.setAddress(addressType.getName() + ", " + addressType.getStreet1() + ", "
//                        + addressType.getCityName() + ", " + addressType.getCountryName());
//
//                customer.setPhone(payerInfoType.getContactPhone());
//                customer.setEmail(payerInfoType.getPayer());
//
//                //
//                session.put("paypalCustomer", customer);
//                session.put("token", token);
//                session.put("PayerID", payerID);
//
//                System.out.println("Get Exp Checkout Status" + responseDetailsType.getCheckoutStatus());
//
//                return SUCCESS;
//            } else {
//                List<ErrorType> errorTypes = response.getErrors();
//                System.out.println("API Error Message : " + errorTypes.get(0).getLongMessage());
//
//                addActionError("Cannot Checkout with Paypal at the moment. (Get)");
//            }
//        } catch (Exception ex) {
//            Logger.getLogger(PaypalAction.class.getName()).log(Level.SEVERE, null, ex);
//        }
//
//        return ERROR;
//    }
//
//    @Action(value = "doExpressCheckout", results = {
//        @Result(name = "success", location = "/processOrderSuccess.jsp"),
//        @Result(name = "error", location = "/shoppingCart.jsp")
//    })
//    public String doExpressCheckout() {
//        Map session = ActionContext.getContext().getSession();
//        ShoppingCart sc = (ShoppingCart) session.get("shoppingCart");
//        List<ShoppingCartItem> scis = sc.getShoppingCartItemList();
//
//
//        DoExpressCheckoutPaymentReq decpr = new DoExpressCheckoutPaymentReq();
//        DoExpressCheckoutPaymentRequestDetailsType decprdt = new DoExpressCheckoutPaymentRequestDetailsType();
//
//        decprdt.setToken((String) session.get("token"));
//        decprdt.setPayerID((String) session.get("PayerID"));
//        //
//        session.remove("token");
//        session.remove("PayerID");
//
//        List<PaymentDetailsType> pdts = new ArrayList<PaymentDetailsType>();
//        //
//        PaymentDetailsType pdt = new PaymentDetailsType();
//        pdt.setPaymentAction(PaymentActionCodeType.SALE);
//
//        BasicAmountType bat = new BasicAmountType(CurrencyCodeType.USD, "" + String.format("%1$,.2f", sc.getTotalAmount()));
//        pdt.setOrderTotal(bat);
//        pdt.setItemTotal(bat);
//
//        SellerDetailsType sdt = new SellerDetailsType();
//        sdt.setPayPalAccountID("escape2008v8-facilitator@gmail.com");
//        pdt.setSellerDetails(sdt);
//
//        //
//        List<PaymentDetailsItemType> pdits = new ArrayList<PaymentDetailsItemType>();
//
//        for (ShoppingCartItem sci : scis) {
//            PaymentDetailsItemType pdit = new PaymentDetailsItemType();
//
//            pdit.setAmount(new BasicAmountType(CurrencyCodeType.USD, "" + sci.getPrice()));
//            pdit.setQuantity(sci.getQuantity());
//            pdit.setName(sci.getProduct().getName());
//            pdit.setNumber(sci.getProduct().getCode());
//            pdit.setDescription(sci.getProduct().getSummary());
//
//            pdits.add(pdit);
//        }
//
//        //
//        pdt.setPaymentDetailsItem(pdits);
//
//        pdts.add(pdt);
//
//        //
//        decprdt.setPaymentDetails(pdts);
//
//        DoExpressCheckoutPaymentRequestType decprt = new DoExpressCheckoutPaymentRequestType(decprdt);
//        decpr.setDoExpressCheckoutPaymentRequest(decprt);
//
//        try {
//            PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(map);
//
//            DoExpressCheckoutPaymentResponseType response = service.doExpressCheckoutPayment(decpr);
//
//            if (response.getAck().getValue().equalsIgnoreCase("success")) {
//                PaymentInfoType paymentInfo = null;
//
//                Iterator<PaymentInfoType> paymentInfoIterator = response.getDoExpressCheckoutPaymentResponseDetails().getPaymentInfo().iterator();
//
//                while (paymentInfoIterator.hasNext()) {
//                    paymentInfo = paymentInfoIterator.next();
//                }
//
////                response.getDoExpressCheckoutPaymentResponseDetails().getPaymentInfo().get(0).getReasonCode().getValue();
////                response.getDoExpressCheckoutPaymentResponseDetails().getPaymentInfo().get(0).getPaymentStatus().getValue();
//
//                //insert DB
//                Customer customer = (Customer) session.get("currentCustomer");
//                Customer paypalCustomer = (Customer) session.get("paypalCustomer");
//
//                if (customer == null) {
//                    customer = paypalCustomer;
//                }
//
//                if (customer != null) {
//                    Order order = sc.convertToOrder();
//                    Date date = new Date();
//
//                    order.setCustomer(customer);
//                    order.setCreateTime(date);
//                    order.setOrderStatus("Paypal - " + paymentInfo.getPaymentStatus().getValue());
//                    order.setPaypalTransactionId(paymentInfo.getTransactionID());
//                    order.setPaypalPaymentStatus(paymentInfo.getPaymentStatus().getValue());
//                    order.setPaypalReasonCode(paymentInfo.getReasonCode().getValue());
//
//                    TransactionDAO transactionDAO = new TransactionDAO();
//
//                    Integer createResult = transactionDAO.createOrderWithPaypal(order);
//
//                    if (createResult != null) {
//                        session.remove("shoppingCart");
//                        if (session.get("username") == null) {
//                            session.remove("currentCustomer");
//                        }
//                        addActionMessage("" + createResult + " - Paypal Payment");
//
//                        return SUCCESS;
//                    } else {
//                        addActionError("Checkout with Paypal failed. (Insert DB)");
//                        session.remove("currentCustomer");
//
//                        return ERROR;
//                    }
//                }
//            } else {
//                List<ErrorType> errorTypes = response.getErrors();
//                System.out.println("API Error Message : " + errorTypes.get(0).getLongMessage());
//
//                addActionError("Cannot Checkout with Paypal at the moment. (Do)");
//            }
//        } catch (Exception ex) {
//            Logger.getLogger(PaypalAction.class.getName()).log(Level.SEVERE, null, ex);
//        }
//
//        return ERROR;
//    }
//}
